from rest_framework.views import APIView
from django.http import JsonResponse
from rest_framework import status
import requests
import os
import uuid
from django.conf import settings

# 外部 API 配置
# 这里用的是picgo免费图床，地址：https://www.picgo.net/ 请自己去申请或者更换其他图床的API
EXTERNAL_API_URL = "https://www.picgo.net/api/1/upload"
EXTERNAL_API_KEY = ""  # 替换为你的 API 密钥

class FileUploadView(APIView):
    def post(self, request, format=None):
        if 'file' not in request.FILES:
            return JsonResponse({"code": "400", "data": None, "message": "请上传文件", "ok": "false"},
                                status=status.HTTP_400_BAD_REQUEST)

        file = request.FILES['file']

        try:
            # 确保文件内容不为空
            if not file.size:
                return JsonResponse({"code": "400", "data": None, "message": "文件为空", "ok": "false"},
                                    status=status.HTTP_400_BAD_REQUEST)

            # 生成唯一的文件名
            unique_filename = f"{uuid.uuid4()}{os.path.splitext(file.name)[1]}"

            # 构建本地存储路径
            media_image_path = os.path.join(settings.MEDIA_ROOT, 'image')
            if not os.path.exists(media_image_path):
                os.makedirs(media_image_path)
            local_file_path = os.path.join(media_image_path, unique_filename)

            # 保存文件到本地
            with open(local_file_path, 'wb') as destination:
                for chunk in file.chunks():
                    destination.write(chunk)

            # 调用外部 API 进行文件上传
            external_response = self.upload_to_external_api(local_file_path)

            if external_response.status_code == 200:
                external_data = external_response.json()
                external_file_url = external_data.get("image", {}).get("url", "")

                # 返回成功响应
                return JsonResponse({
                    "code": "200",
                    "data": external_file_url,
                    "message": "上传成功",
                    "ok": "true"
                }, status=status.HTTP_200_OK)
            else:
                # 删除本地保存的文件
                os.remove(local_file_path)
                return JsonResponse({
                    "code": "500",
                    "data": None,
                    "message": f"外部 API 上传失败: {external_response.text}",
                    "ok": "false"
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        except Exception as e:
            # 删除本地保存的文件
            if 'local_file_path' in locals() and os.path.exists(local_file_path):
                os.remove(local_file_path)
            # 返回失败响应
            return JsonResponse({"code": "500", "data": None, "message": f"上传失败: {str(e)}", "ok": "false"},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def upload_to_external_api(self, file_path):
        headers = {
            "X-API-Key": EXTERNAL_API_KEY,
        }

        with open(file_path, 'rb') as file:
            files = {
                "source": (os.path.basename(file_path), file, "image/*")
            }
            response = requests.post(EXTERNAL_API_URL, headers=headers, files=files)
        return response